# Copyright (c) 2024 Project CHIP Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import xml.etree.ElementTree as ElementTree

from matter.yamltests.pseudo_clusters.pseudo_clusters import get_default_pseudo_clusters

SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
WARNING = ("<!---\n"
           "This file is automatically generated by a script.\n"
           "DO NOT HAND-EDIT THIS FILE.\n"
           f"Script: {os.path.basename(__file__)}\n"
           "-->\n\n")


def create_tables():
    pseudo_clusters = get_default_pseudo_clusters()

    doc_path = os.path.abspath(os.path.join(
        SCRIPT_DIR, '..', '..', 'docs', 'testing', 'yaml_pseudocluster.md'))
    with open(doc_path, "w") as f:
        f.writelines(WARNING)
        f.writelines('# YAML Pseudo-clusters\n\n')

        for cluster in pseudo_clusters.clusters:
            f.writelines(f'\n\n{cluster.name}\n')
            f.writelines('|command|args|arg type| arg optional|\n')
            f.writelines('|:---|:---|:---|:---|\n')

            et = ElementTree.fromstring(cluster.definition)
            cluster_xml = next(et.iter('cluster'))
            for command_xml in cluster_xml.iter('command'):
                cmd = command_xml.get('name')
                arg = '<br />'.join([arg_xml.get('name')
                                    for arg_xml in command_xml.iter('arg')])
                argtype = '<br />'.join([arg_xml.get('type')
                                        for arg_xml in command_xml.iter('arg')])
                optional = '<br />'.join([arg_xml.get('optional', 'false')
                                         for arg_xml in command_xml.iter('arg')])

                f.writelines(f'|{cmd}|{arg}|{argtype}|{optional}|\n')


create_tables()
